import { DownOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, Divider, message, Modal, Descriptions } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { queryPatrolJobItem, updatePatrolJobItem, addPatrolJobItem, removePatrolJobItem, getPatrolJobInfo } from '@/services/patroljob';
import { queryDictByType } from '@/services/dict';
import { queryAreaTree } from '@/services/area';

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addPatrolJobItem(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updatePatrolJobItem(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

//删除单个
const handleRemove = async (fields: any) => {
  const hide = message.loading('正在删除');
  try {
    await removePatrolJobItem({id: fields.id});
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

const { confirm } = Modal;

const TableList: React.FC = (props:any) => {
  const { params } = props.match;
  const [areaData, setAreaData] = useState<API.TreeNodeItem[]>([]);
  const [levelValues, setLevelValues] = useState<API.DictItem[]>([]);
  const [typeValues, setTypeValues] = useState<API.DictItem[]>([]);
  const [leveEnumValues, setLeveEnumValues] = useState({});
  const [typeEnumValues, setTypeEnumValues] = useState({});
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<API.PatrolJobItem>({});
  const [pageValues, setPageValues] = useState<API.PatrolJob>({});
  const actionRef = useRef<ActionType>();

  const columns: ProColumns[] = [
    {
      title: '巡检区域',
      dataIndex: 'areaName',
    },
    {
      title: '巡检位置',
      dataIndex: 'position',
    },
    {
      title: '巡检内容',
      dataIndex: 'content',
    },
    {
      title: '重要性',
      dataIndex: 'importantLevel',
      valueEnum: leveEnumValues,
    },
    {
      title: '项目类别',
      dataIndex: 'patroItemlType',
      valueEnum: typeEnumValues,
    },
    {
      title: '是否启用',
      dataIndex: 'useState',
      hideInSearch: true,
      valueEnum: {
        1: { text: '启用', status: 'Success' },
        0: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a onClick={async () => {
              handleUpdateModalVisible(true);
              setFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => {
              confirm({
                title: '您确定要删除吗?',
                icon: <ExclamationCircleOutlined />,
                async onOk() {
                  await handleRemove(record);
                  actionRef.current?.reload();
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }}
          >
             删除
          </a>
        </>
      ),
    },
  ];

  const setStateData = async () => {
    const patrol = await getPatrolJobInfo(params);
    setPageValues(patrol);
    let trees = await queryAreaTree();
    setAreaData(trees);
    const levellist = await queryDictByType({ type: '7' });

    let ldata = {};
    if (levellist && levellist.length > 0) {
      levellist.forEach((item:any) => {
        ldata[item.dictCode] = item.dictValue;
      });
    }
    setLeveEnumValues(ldata);
    setLevelValues(levellist);
    const typelist = await queryDictByType({ type: '4' });
    let tdata = {};
    if (typelist && typelist.length > 0) {
      typelist.forEach((item:any) => {
        tdata[item.dictCode] = item.dictValue;
      });
    }
    setTypeEnumValues(tdata);
    setTypeValues(typelist);
  };

  useEffect(() => {
     setStateData();
  }, []);

  return (
    <>
      <Descriptions title="任务信息" style={{ margin: '0px', padding: '24px' }}>
        <Descriptions.Item label="任务名称">{pageValues.jobName}</Descriptions.Item>
        <Descriptions.Item label="责任部门">{pageValues.deptName}</Descriptions.Item>
        <Descriptions.Item label="开始时间">{pageValues.startTime}</Descriptions.Item>
        <Descriptions.Item label="结束时间">{pageValues.endTime}</Descriptions.Item>
        <Descriptions.Item label="描述">{pageValues.memo}</Descriptions.Item>
      </Descriptions>
      <ProTable
        headerTitle=""
        rowKey="id"
        actionRef={actionRef}
        tableAlertRender={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新增
          </Button>
        ]}
        toolbar={{
          settings: []
        }}
        search={false}
        rowSelection={{}}
        request={(param) => queryPatrolJobItem({ ...param, ...params })}
        columns={columns}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 100,
        }}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            setFormValues({});
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        levelList={levelValues}
        typeList={typeValues}
        treeData={areaData}
        jobId={pageValues.id}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          levelList={levelValues}
          typeList={typeValues}
          treeData={areaData}
          values={formValues}
          jobId={pageValues.id}
        />
      ) : null}
    </>
  );
};

export default TableList;
